package com.maben.async.service.impl;

import com.alibaba.fastjson.JSON;
import com.maben.async.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 异步业务类
 */
@Service
public class AsyncServiceImpl implements AsyncService {
    @Async("taskExecutorForHeavyTasks")
    public void sendEmail(int k) throws Exception {
        for (int i = 0; i < 10; i++) {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(k + ":异步测试：" + i + ",thread:" + JSON.toJSONString(Thread.currentThread()));
        }
    }

    @Async
    public Future<String> sendEmail2(int i) throws Exception {
        if (i % 2 == 0) {
            throw new Exception("Oops, cannot send email!");
        }
        return new AsyncResult<String>(i + "");
    }

}
